package com.bw.broker.component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liuzhihao
 * @version 1.0
 * @description: TODO WebSocket服务
 * @date 2023/11/16 14:26:24
 */
@ServerEndpoint(value = "/imServer/{username}")
@Component
@Slf4j
public class WebSocketServer {

    /**
     *  记录当前在线连接数
     */
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * @description : //TODO 连接建立成功调用的方法
     * @param session
     * @param username
     * @return : void
     * @author : liuzhihao
     * @date : 2023/11/16 14:32:18
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username")String username){
        // 将当前用户加入聊天室
        sessionMap.put(username,session);
        log.info("有新用户加入,username={},当前在线人数为:{}",username,sessionMap.size());
        JSONObject result = new JSONObject();
        JSONArray array = new JSONArray();
        result.put("users",array);

    }
}
